'use strict';

module.exports = app => {
  return async (ctx, next) => {
    ctx.socket.emit('res', 'connected!');
    // 拿到用户通过query 的 username
    const user = ctx.socket.handshake.query.username;
    // 将username 和 id 存到redis 的缓存中
    if (!user) {
      return;
    }
    await app.redis.set(user, ctx.socket.id);

    const userList = await app.redis.get('userList');
    let OutPutList = [];
    if (userList) {
      OutPutList = userList.split(',');
    }
    OutPutList.push(user);
    OutPutList = [ ...new Set(OutPutList) ];
    await app.redis.set('userList', OutPutList.join());

    const nsp = app.io.of('/');
    nsp.emit('login', { userList: OutPutList });

    await next();
    // execute when disconnect.
    console.log('disconnection!');
  };
};
